package com.toman.ui.my;


import android.app.Dialog;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.githang.statusbar.StatusBarCompat;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.squareup.picasso.Picasso;
import com.toman.Adpter.ItemListAdapter;
import com.toman.Enum.NetworkEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.SysUserEntity;
import com.toman.Login.LoginActivity;
import com.toman.MyApplication;
import com.toman.R;
import com.toman.Util.CircleTransform;
import com.toman.Util.DefaultAcitonCallback;
import com.toman.Util.DialogUtils;
import com.toman.Util.IntentUtils;
import com.toman.Util.JsonUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.StringUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.ItemListBean;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;

import org.json.JSONException;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidkun.com.versionupdatelibrary.entity.VersionUpdateConfig;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Request;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class MyFragment extends Fragment {

    Unbinder unbinder;

    ItemListAdapter adapter;
    String contents;
    String version;
    String attachfile;
    //     0普通更新   1强制更新
    String mustUpdate = "0";
    List<ItemListBean> list = new ArrayList<ItemListBean>();
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_identity)
    TextView tvIdentity;
    @BindView(R.id.tv_inf)
    TextView tvInf;
    @BindView(R.id.rl_base)
    RelativeLayout rlBase;
    @BindView(R.id.mWifi)
    ImageView mWifi;
    @BindView(R.id.ll_wifi)
    LinearLayout llWifi;
    @BindView(R.id.mLockPwd)
    ImageView mLockPwd;
    @BindView(R.id.ll_pwd)
    LinearLayout llPwd;
    @BindView(R.id.mNews)
    ImageView mNews;
    @BindView(R.id.ll_feedback)
    LinearLayout llFeedback;
    @BindView(R.id.ll_about_us)
    ImageView llAboutUs;
    @BindView(R.id.mHongdian)
    TextView mHongdian;
    @BindView(R.id.mSet)
    LinearLayout mSet;
    @BindView(R.id.cv_item)
    FrameLayout cvItem;
    @BindView(R.id.btn_exit)
    Button btnExit;
    MyApplication myApplication;
    @BindView(R.id.iv_update)
    ImageView ivUpdate;
    @BindView(R.id.ll_update)
    LinearLayout llUpdate;
    @BindView(R.id.ll_compamy)
    LinearLayout llCompamy;

    public MyFragment() {
        // Required empty public constructor
    }

    View rootView;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rootView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_my2,
                null);

        ButterKnife.bind(this, rootView);
        initView();

//        test();
    }

    @Override
    public void onResume() {
        super.onResume();
        StatusBarCompat.setStatusBarColor(getActivity(), getResources().getColor(R.color.button_blue), false);
        get();
    }

    private void initView() {
        if ((Boolean) SPUtils.get(getActivity(),"muti_company",false)){
            llCompamy.setVisibility(View.VISIBLE);
        }
        adapter = new ItemListAdapter(getActivity());
        myApplication = (MyApplication) getActivity().getApplication();
        if (myApplication.getBean() != null) {
            SysUserEntity bean = myApplication.getBean();
            tvName.setText(bean.getRealName());
            tvIdentity.setText(bean.getPostInformation());
            if (!StringUtils.isEmpty(bean.getPhotoUrl())) {
                Picasso.with(getActivity()).load(bean.getPhotoUrl()).error(R.mipmap.my_icon_head).transform(new CircleTransform()).into(ivHead);
            }

        }

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the item_data for this fragment
        ViewGroup perentView = (ViewGroup) rootView.getParent();
        if (perentView != null) {
            perentView.removeAllViewsInLayout();
        }

        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    public void initList() {

        list.clear();
        String items[] = new String[]{"刘晨", "吴典", "翔", "线上"};

        for (int i = 0; i < items.length; i++) {
            ItemListBean bean = new ItemListBean(items[i], i + "");
            list.add(bean);
        }
        adapter.refreshData(list);
    }

    public void get() {
        String token = (String) SPUtils.get(getActivity(), "token", "");
        OkHttpUtils
                .get(NewBaseUrl.user_info_get)
                .params("token", token)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "人员信息: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");

                        ViewUtil.lagout(code, getActivity());
                        if (code == 0) {
                            SysUserEntity bean = (SysUserEntity) JSON.parseObject(jsonObj.getString("user"), SysUserEntity.class);
                            myApplication.setBean(bean);
                            try {
                                tvName.setText(bean.getRealName());
                                tvIdentity.setText(bean.getPostInformation());
                                if (!StringUtils.isEmpty(bean.getPhotoUrl())) {
                                    Picasso.with(getActivity()).load(bean.getPhotoUrl()).error(R.mipmap.my_icon_head).transform(new CircleTransform()).into(ivHead);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        } else {
                            ToastUtil.makeText(getActivity(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    @OnClick({R.id.ll_wifi, R.id.ll_pwd, R.id.ll_feedback, R.id.mSet, R.id.btn_exit, R.id.rl_base, R.id.ll_update,R.id.ll_compamy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_wifi:
                IntentUtils.startActivity(getActivity(), WifiActivity.class);

                break;
            case R.id.ll_pwd:
                IntentUtils.startActivity(getActivity(), PwdEditActivity.class);

                break;
            case R.id.ll_feedback:
                IntentUtils.startActivity(getActivity(), FeedBackActivity.class);
                break;
            case R.id.rl_base:
                IntentUtils.startActivity(getActivity(), InfActivity.class);
                break;
            case R.id.mSet:
                IntentUtils.startActivity(getActivity(), AboutUsActivity.class);

                break;

            case R.id.btn_exit:
                exit();
                break;
            case R.id.ll_update:

                appUpdata();
                break;
            case R.id.ll_compamy:
//                DialogUtils.showDialog(getActivity(), NetworkEnum.MUIICONPANY, "","list", new DefaultAcitonCallback() {
//                    @Override
//                    public void run(ItemListBean bean1, Dialog dialog) {
//                        ItemListBean bean = bean1;
//
//                        String companyId = bean.getID();
//                        SPUtils.put(getActivity(), "cpy_id",companyId);
//                        update(companyId,bean1.getName());
//                        dialog.dismiss();
//                    }
//                });
                change();

                break;
        }
    }
    public void update(String companyId,String name) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("companyId",companyId);


        String str = JsonUtils.obj2JsonString(map);
        ToastUtil.print("发送json" + str);
        OkHttpUtils
                .post(NewBaseUrl.user_update_post_user)
                .headers("token", (String) SPUtils.get(getActivity(),"token",""))
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "编辑用户: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getActivity());

                        if (code == 0) {
ToastUtil.makeText(getActivity(),"成功切换到"+name);

                        } else {
                            ToastUtil.makeText(getActivity(), jsonObj.getString("msg"));
                        }
                    }
                });
    }
    public void appUpdata() {
        OkHttpUtils
                .get(NewBaseUrl.app_update)
                .params("platform","1")
                .params("token", (String) SPUtils.get(getActivity(), "token", ""))
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        try {
                            org.json.JSONObject js = new org.json.JSONObject(result);
                            int code = js.getInt("code");
                            ViewUtil.lagout(code, getActivity());
                            if (code == 0) {
                                org.json.JSONObject data = js.getJSONObject("data");
                                Log.i("test", "版本更新： " + data.toString());

                                contents = data.getString("content");
                                version = data.getString("version");
                                attachfile = data.getString("attachfile");
                                try {
                                    mustUpdate = data.getString("mustUpdate");
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                if (version.equals(getVersionName())) {
                                    Toast.makeText(getContext(), "当前已是最新版本!", Toast.LENGTH_SHORT).show();

//                                    DelDialog();
                                } else {
                                    Log.i("test", "执行了: ");
                                    DelDialog();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private String getVersionName() throws Exception {
        // 获取packagemanager的实例
        PackageManager packageManager = getActivity().getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(getActivity().getPackageName(), 0);
        String version = packInfo.versionName;
        return version;
    }

    public void DelDialog() {
        final AlertDialog dialog = new AlertDialog.Builder(getContext()).create();
        dialog.show();
        dialog.getWindow().setContentView(R.layout.del_layouts);
        dialog.setCancelable(false);
        TextView mLine_Names = (TextView) dialog.findViewById(R.id.mLine_Names);
        mLine_Names.setText(contents);
        if (mustUpdate.equals("1")) {
            Button button = dialog.getWindow().findViewById(R.id.mNoDimsss);
            button.setText("退出");
        }

        dialog.getWindow().findViewById(R.id.mNoDimsss).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mustUpdate.equals("0")) {
                    dialog.dismiss();
                } else {
                    dialog.dismiss();
//                    IntentUtils.startActivity(getActivity(), LoginActivity.class);
                    getActivity().finish();

                }
            }
        });
        dialog.getWindow().findViewById(R.id.mDetermines).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File appDir = new File(getActivity().getFilesDir().getPath());

                ToastUtil.print(appDir.getAbsolutePath());
                if (!appDir.exists()) {
                    appDir.mkdir();
                }
                dialog.dismiss();
                VersionUpdateConfig.getInstance()//获取配置实例
                        .setContext(getActivity())//设置上下文
                        .setDownLoadURL(attachfile)//设置文件下载链接
                        .setNewVersion(version)//设置即将下载的APK的版本号,避免重复下载
//                         .setFileSavePath(appDir.getPath())//设置文件保存路径（可不设置）
                        .setNotificationIconRes(R.mipmap.baselogo)//设置通知图标
                        .setNotificationSmallIconRes(R.mipmap.baselogo)//设置通知小图标
                        .setNotificationTitle("陀曼智造(版本更新)")//设置通知标题
                        .startDownLoad();//开始下载
                Toast.makeText(getContext(), "开始下载...", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void exit() {
        MobclickAgent.onProfileSignOff();
        //                友盟解绑别名
        IntentUtils.startActivity(getActivity(), LoginActivity.class);
        PushAgent pushAgent = myApplication.mPushAgent;
        String userid = (String) SPUtils.get(getActivity(), "userid", "");
        pushAgent.deleteAlias(userid, "toman", new UTrack.ICallBack() {
            @Override
            public void onMessage(boolean isSuccess, String message) {
                if (isSuccess) {
                    ToastUtil.print("解绑成功：" + message);
                } else {
                    ToastUtil.print("解绑失败：" + message);

                }
            }
        });
        String phone = (String) SPUtils.get(getContext(), "phone", "");
        String pwd = (String) SPUtils.get(getContext(), "pwd", "");
        SPUtils.clear(getContext());
        SPUtils.put(getContext(), "phone", phone);
        SPUtils.put(getContext(), "pwd", pwd);
        getActivity().finish();
    }
    private void change() {
        MobclickAgent.onProfileSignOff();
        //                友盟解绑别名
        Bundle bundle=new Bundle();
        bundle.putBoolean("change",true);
        IntentUtils.startActivity(getActivity(), LoginActivity.class,bundle );
        PushAgent pushAgent = myApplication.mPushAgent;
        String userid = (String) SPUtils.get(getActivity(), "userid", "");
        pushAgent.deleteAlias(userid, "toman", new UTrack.ICallBack() {
            @Override
            public void onMessage(boolean isSuccess, String message) {
                if (isSuccess) {
                    ToastUtil.print("解绑成功：" + message);
                } else {
                    ToastUtil.print("解绑失败：" + message);

                }
            }
        });
        String phone = (String) SPUtils.get(getContext(), "phone", "");
        String pwd = (String) SPUtils.get(getContext(), "pwd", "");
        SPUtils.clear(getContext());
        SPUtils.put(getContext(), "phone", phone);
        SPUtils.put(getContext(), "pwd", pwd);
        getActivity().finish();
    }
}
